package com.example.canvasdemo.ui

import android.content.Intent
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.speech.tts.TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.example.canvasdemo.R
import com.example.canvasdemo.model.DrawingResponse
import com.example.canvasdemo.network.ApiService
import com.example.canvasdemo.network.RetrofitClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.Locale

class GuessWordActivity : AppCompatActivity(), TextToSpeech.OnInitListener {
    private var roomId: Long = 0
    private var word: String = ""
    private var hint: String = ""
    private var drawing: String = ""
    private lateinit var tts: TextToSpeech
    private var userId: Long = 0
    private var userName: String = "Guest"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_guess_word)

        tts = TextToSpeech(this, this)

        // 获取房间ID
        roomId = intent.getLongExtra("room_id", 0L)
        if (roomId == 0L) {
            Toast.makeText(this, "无效的房间ID", Toast.LENGTH_SHORT).show()
            finish()
            return
        }

        fetchLastDrawingAndHint()

        // 提交猜词逻辑
        findViewById<Button>(R.id.btnSubmitGuess).setOnClickListener {
            val guess = findViewById<EditText>(R.id.etGuess).text.toString().trim()

            if (guess.equals(word, ignoreCase = true)) {
                // 播报猜对了
                tts.speak("猜对了！", TextToSpeech.QUEUE_FLUSH, null, null)
                Toast.makeText(this, "猜对了！", Toast.LENGTH_SHORT).show()
                val roomId: Long = roomId
                val userId: Long = userId
                val userName: String = userName
                val intent = Intent(this@GuessWordActivity, RoomDetailActivity::class.java)
                intent.putExtra("room_id", roomId)
                intent.putExtra("userId", userId)
                intent.putExtra("userName", userName)
                startActivity(intent)
                finish() // 结束当前活动，防止用户返回
            } else {
                Toast.makeText(this, "再试试！", Toast.LENGTH_SHORT).show()
            }
        }
    }

    // TTS 初始化完成后的回调
    override fun onInit(status: Int) {
        if (status == TextToSpeech.SUCCESS) {
            val langResult = tts.setLanguage(Locale.CHINA)
            if (langResult == LANG_COUNTRY_VAR_AVAILABLE) {
                Log.d("TTS", "TTS初始化成功")
            } else {
                Log.e("TTS", "TTS初始化失败，语言不可用")
            }
        } else {
            Log.e("TTS", "TTS初始化失败")
        }
    }

    // 获取绘画和提示信息
    private fun fetchLastDrawingAndHint() {
        val apiService = RetrofitClient.instance.create(ApiService::class.java)
        Log.d("FetchDrawing", "开始请求获取绘画和提示")

        apiService.getLastDrawingAndHint(roomId).enqueue(object : Callback<DrawingResponse> {
            override fun onResponse(call: Call<DrawingResponse>, response: Response<DrawingResponse>) {
                if (response.isSuccessful) {
                    // 打印响应原始数据
                    val responseData = response.body()
                    Log.d("FetchDrawing", "响应数据：$responseData")

                    // 检查是否获取成功
                    if (responseData != null && responseData.success) {
                        // 从 drawingData 中获取提示、单词和绘画数据
                        val hint = responseData.drawingData.hint
                        val word = responseData.drawingData.word
                        val drawing = responseData.drawingData.drawingData

                        Log.d("FetchDrawing", "获取的提示：$hint，单词：$word，绘画数据：$drawing")

                        // 确保数据完整
                        if (hint != null && word != null && drawing != null) {
                            // 更新UI
                            this@GuessWordActivity.hint = hint
                            this@GuessWordActivity.word = word
                            this@GuessWordActivity.drawing = drawing

                            // 播报提示
                            tts.speak("提示：$hint", TextToSpeech.QUEUE_FLUSH, null, null)

                            findViewById<TextView>(R.id.tvWordHint).text = "提示：$hint"
                            displayDrawing(drawing)
                        } else {
                            Log.e("FetchDrawing", "返回的数据缺少提示、单词或绘画数据")
                        }
                    } else {
                        Log.e("FetchDrawing", "获取数据失败，success字段为false")
                        Toast.makeText(this@GuessWordActivity, "获取提示失败", Toast.LENGTH_SHORT).show()
                    }
                } else {
                    Log.e("FetchDrawing", "请求失败，错误码：${response.code()}")
                    Toast.makeText(this@GuessWordActivity, "请求失败", Toast.LENGTH_SHORT).show()
                }
            }

            override fun onFailure(call: Call<DrawingResponse>, t: Throwable) {
                Log.e("FetchDrawing", "请求失败，错误信息：${t.message}")
                Toast.makeText(this@GuessWordActivity, "获取提示失败", Toast.LENGTH_SHORT).show()
            }
        })
    }

    // 显示绘画数据
    private fun displayDrawing(drawing: String) {

        val base64Data = "data:image/png;base64,$drawing"
        Glide.with(this).load(base64Data).into(findViewById(R.id.ivDrawing))
    }

    // 在Activity销毁时关闭TTS
    override fun onDestroy() {
        super.onDestroy()
        if (::tts.isInitialized) {
            tts.stop()
            tts.shutdown()
        }
    }
}








